<template>
  <div>

    <div style="display: flex; justify-content: center;">
      <el-row type="flex" style="width: 50%; margin-top: 10px;">
        <el-button icon="el-icon-back"
                   @click="cancelModify"
                   plain
        >
          取消编辑</el-button>
      </el-row>
    </div>

    <el-form :model="form"
             label-width="auto"
             ref="form"
             :rules="rules"
             v-loading="submitLoading"
             element-loading-text="正在上传中"
             element-loading-spinner="el-icon-loading"
             class="report-submit-box">

      <h3 class="report-submit-title">
        <img src="../../assets/image/submit-report.png" alt="" style="width: 150px">
      </h3>


      <el-form-item label="缺陷描述" prop="description">
        <el-input
            type="textarea"
            :autosize="{ minRows: 4 }"
            placeholder="请在此处进行缺陷描述"
            maxlength="200"
            show-word-limit
            v-model="form.description">
        </el-input>
      </el-form-item>

      <el-form-item label="缺陷复现步骤" prop="steps">
        <el-input
            type="textarea"
            :autosize="{ minRows: 4 }"
            placeholder="请在此处叙述缺陷复现步骤"
            maxlength="200"
            show-word-limit
            v-model="form.steps">
        </el-input>
      </el-form-item>

      <el-form-item label="缺陷截图上传">
        <el-row type="flex">
          <el-upload
              ref="upload"
              action="#"
              accept="image/jpeg,image/png"
              :before-upload="onBeforeUpload"
              :on-preview="handlePreview"
              :on-change="handleChange"
              :file-list="form.screenshot"
              :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1MB</div>
          </el-upload>
        </el-row>
      </el-form-item>

      <el-form-item>
        <el-button class="btn" id="register-btn" type="primary" @click="onSubmit('form')">提交</el-button>
<!--        todo 需要补全：点击编辑提交之后，更新报告的一系列逻辑-->
      </el-form-item>

    </el-form>

  </div>
</template>

<script>
import {Debounce} from "@/utils/Debounce.js";
import {submitReport} from "@/api/worker";
import {uploadFile} from "@/api/file";
import {createScreenshot, getReportByReportID, getScreenshot} from "@/api/report";
import {createTaskFile} from "@/api/task";
import {modifyReport} from "@/api/worker";
import {getReportByTaskIDAndWorkerID} from "@/api/worker";


export default {
  name: 'SubmitReport',
  data() {

    return {

      form: {
        description: '',
        steps: '',
        //我不会填充截图。。
        //screenshot: []
      },

      submitLoading: false,

      rules: {
        description: [
          {required: true, message: '请填写缺陷描述', trigger: 'blur'}
        ],
        steps: [
          {required: true, message: '请填写缺陷复现步骤', trigger: 'blur'}
        ],
        screenshot: [],
      },

      fileList: [],
    };

  },
  methods: {
    cancelModify(){
      this.$confirm('确定放弃修改吗？取消编辑后，您已经修改的内容不会被保存', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push(`/worker/mytasks/report/${this.$route.params.taskid}`)
      }).catch(() => {
      })
    },

    // 防抖
    onSubmit: Debounce(function (formName) {
      this.$confirm('确定提交报告吗？此版本将会成为您的最新版本', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submitLoading = true;
            this.handleSubmitReport(this.form);
          } else {
            this.$message.error('提交失败，请检查您的信息！')
            return false;
          }
        });
      }).catch(() => {
      })
    }, 1000),

    handleSubmitReport(payload) {
      if (this.fileList.length < 1) {
        this.$message.error('提交失败！请选择截图并上传！');
        return;
      }

      payload['workerid'] = sessionStorage.getItem('userid');
      payload['taskid'] = this.$route.params.taskid;
      // 对res的处理方法是直接复制他们之前的submitReport
      const res1 = modifyReport(payload).then(res =>{
        if (res1.code === 200) {
          this.$message.success('提交成功！');
          this.$router.push('/worker/mytasks/executing');

          const reportId = res1.data.id;
          // 上传文件
          const formData = new window.FormData();
          formData.append("file", this.fileList[0].raw);
          let res = uploadFile(formData);

          // 写数据库
          if (res.code === 200) {
            const fileInfo = {
              reportId: reportId,
              url: res.data.name
            };
            createScreenshot(fileInfo).then(res => {
              console.log(res);
            });
          }
        } else {
          this.$message.error('发布失败！服务器异常');
        }
      })
    },


    onBeforeUpload(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/png';
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
      }
      return isIMAGE && isLt1M;
    },


    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = []
    },


    handlePreview(file) {
      console.log(file);
    },


    handleChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.shift();
      }
      this.fileList = fileList;
    },

    // lyl 加载之前的报告内容
    // 用的是taskId+workerId获取报告内容
    loadPrevReportContent() {
      const taskid = this.$route.params.taskid;
      const uid = sessionStorage.getItem('userid');
      // copied usage from getReport
      getReportByTaskIDAndWorkerID(taskid,uid).then(res=>{
        if (res.code !== 200) {
          return this.$message.error('报告不存在！');
        }
        const obj = res.data;
        for (let key of Object.keys(obj)) {
          if (key === 'type') {
            if (obj['type'] === 'function_test') this.form['type'] = '功能测试';
            else if (obj['type'] === 'performance_test') this.form['type'] = '性能测试';
            else if (obj['type'] === 'bug_explore') this.form['type'] = 'Bug探索';
          } else {
            this.form[key] = obj[key];
          }
        }
      })
    },
  },
  mounted() {
    this.loadPrevReportContent();
  }
}
</script>

<style scoped>
.report-submit-box {
  border: 1px solid #DCDFE6;
  width: 45%;
  margin: 10px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 8px #909399;

  background-color: #fff;
}


.btn, a {
  margin-right: 20%;
}

</style>